from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import pandas as pd
class Grap:
    def __init__(self):
        # 设置驱动的路径,这是 selenium4之后的新写法
        self.service = Service(executable_path=r"C:\Program Files\Google\Chrome\Application\chromedriver.exe")
        # 实例化浏览器对象
        self.driver = webdriver.Chrome(service=self.service)

        self.df = pd.DataFrame(columns=['id', 'title', 'score','star','year','duration','director','actors','vote'])
        self.save_path = "./auto/data/douban.csv"
        self.comment = "./auto/data/comment.txt"
    # 进入初始页面
    def main(self):
        self.driver.get("https://movie.douban.com/cinema/nowplaying/leshan/")
        time.sleep(2)
        elements = self.driver.find_elements(By.XPATH, "//ul[@class='lists']/li[@class='list-item']")

        i=0
        for element in elements:
            did = element.get_attribute("id")
            dtitle = element.get_attribute("data-title")
            dscore = element.get_attribute("data-score")
            dstar = element.get_attribute("data-star")
            dyear = element.get_attribute("data-release")
            ddura = element.get_attribute("data-duration")
            ddirect = element.get_attribute("data-director")
            dactor = element.get_attribute("data-actors")
            dvote = element.get_attribute("data-votecount")
            # # 创建一个新行的字典
            # new_row = {'id':did, 'title':dtitle, 'score':dscore,'star':dstar,'year':dyear, \
            #     'duration':ddura,'director':ddirect,'actors':dactor,'vote':dvote}
 
            # 将新行添加到DataFrame中
            self.df.loc[i] = [did, dtitle, dscore,dstar,dyear,ddura,ddirect,dactor,dvote]
            time.sleep(1)
            i = i+1
        self.df.to_csv(self.save_path,index=None)

    def get_num(self):
        f = open(self.comment,"w",encoding="utf-8")
        a = 1000
        self.driver.get("https://movie.douban.com/subject/36653918/comments?status=P")
        while(a>0):
            elements = self.driver.find_elements(By.XPATH, "//p[@class=' comment-content']/span[@class='short']")
            elements2 = self.driver.find_elements(By.XPATH, "//span[@class='comment-info']/span[contains(@class,'rating')]")
            for ele,ele2 in zip(elements,elements2):
                f.write(ele2.get_attribute("title")+"\t"+ele.text+"\n")
                a = a - 1
        
            element = self.driver.find_elements(By.XPATH, "//div[@id='paginator']/a")
            try:
                link = element[2].get_attribute("href")
                self.driver.get(link)
            except:
                break

if __name__ == '__main__':
    g = Grap()
    g.get_num()
